package com.coffee.mybatis;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Songkui
 * @since 2019/10/29 9:30
 */
public class CoffeeCodeGenerator {

    private InjectionConfig getInjectionConfig(PackageConfig packageConfig, CoffeeCodeGeneratorConfig config) {
        String template = "/template";
        String parent = packageConfig.getParent();
        String replace = "";
        if (StrUtil.isNotBlank(parent)) {
            replace = parent.replace(".", "/");
        }

        String srcJava = "/src/test/java/" + replace + "/";
        String srcRes = "/src/test/resources";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        String templatePath = template + "/mapper.xml.ftl";
        // 自定义配置:mapper.xml
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名
                return config.getProjectPath() + srcRes + "/mapper/" + packageConfig.getModuleName() + "/" + tableInfo.getXmlName() + StringPool.DOT_XML;
            }
        });

        // 自定义配置:controller.java
        templatePath = template + "/controller.java.ftl";
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名
                return config.getProjectPath() + srcJava + "/controller/" + tableInfo.getControllerName() + StringPool.DOT_JAVA;
            }
        });

        // 自定义配置:dao.java
        templatePath = template + "/mapper.java.ftl";
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名
                return config.getProjectPath() + srcJava + "/repository/mapper/" + tableInfo.getMapperName() + StringPool.DOT_JAVA;
            }
        });

        // 自定义配置:xxPo.java
        templatePath = template + "/entity.java.ftl";
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名
                return config.getProjectPath() + srcJava + "/entity/" + tableInfo.getEntityName() + StringPool.DOT_JAVA;
            }
        });


        // 自定义配置:xxService.java
        templatePath = template + "/Repository.java.ftl";
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名
                return config.getProjectPath() + srcJava + "/repository/" + tableInfo.getServiceName() + StringPool.DOT_JAVA;
            }
        });

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
            }
        };
        cfg.setFileOutConfigList(focList);
        return cfg;
    }

    /* 数据源配置 */
    private DataSourceConfig getDataSourceConfig(CoffeeCodeGeneratorConfig config) {
        DataSourceConfig dsConfig = new DataSourceConfig();
        dsConfig.setDriverName(config.getDsDriver());
        dsConfig.setUrl(config.getDsUrl());
        dsConfig.setUsername(config.getDsUserName());
        dsConfig.setPassword(config.getDsPassword());
        return dsConfig;
    }


    /* 全局配置 */
    private GlobalConfig getGlobalConfig(CoffeeCodeGeneratorConfig config) {
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setOutputDir(config.getProjectPath());
        globalConfig.setAuthor(config.getAuthor());
        globalConfig.setOpen(false);
        globalConfig.setBaseResultMap(true);
        globalConfig.setBaseColumnList(true);
        globalConfig.setFileOverride(true);
        globalConfig.setEnableCache(true);
        globalConfig.setIdType(IdType.ASSIGN_ID);
        globalConfig.setServiceName("%sRepository");
        globalConfig.setEntityName("%sEntity");
        globalConfig.setControllerName("%sController");
        globalConfig.setMapperName("%sMapper");
        globalConfig.setXmlName("%sMapper");
        return globalConfig;
    }

    public void doGenerator(CoffeeCodeGeneratorConfig config) {
        GlobalConfig globalConfig = this.getGlobalConfig(config);  // 全局配置
        DataSourceConfig dataSourceConfig = this.getDataSourceConfig(config); // 数据源配置
        StrategyConfig strategyConfig = this.getStrategyConfig(config);  // 策略配置
        PackageConfig packageConfig = this.getPackageConfig(config);  // 包配置
        InjectionConfig injectionConfig = this.getInjectionConfig(packageConfig, config);   // 自定义配置

        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        mpg.setGlobalConfig(globalConfig)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(packageConfig)
                .setCfg(injectionConfig);

        // 设置模板配置
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null)
                .setController(null)
                .setService(null)
                .setServiceImpl(null)
                .setEntity(null)
                .setMapper(null);
        // 设置模板
        mpg.setTemplate(templateConfig)
                .setTemplateEngine(new FreemarkerTemplateEngine())  // 设置模板引擎
                .execute();

    }

    /**
     * 策略配置
     */
    private StrategyConfig getStrategyConfig(CoffeeCodeGeneratorConfig config) {
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass("com.coffee.mybatis.BaseEntity"); // 公共父类
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 是否为链式模型（默认 false）
        strategy.setChainModel(true);
        // 是否生成字段常量（默认 false）
//        strategy.setEntityColumnConstant(true);
        // 公共父类
//        strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("creatorId", "create_time", "updater_id", "update_time", "status_bit");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setEntityBooleanColumnRemoveIsPrefix(true);
        strategy.setEntityTableFieldAnnotationEnable(true);

        strategy.setInclude(config.getIncludeTableNames()); //** 需要生成的表名
        strategy.setTablePrefix(config.getTablePrefixes());  //表名前缀
        return strategy;
    }


    /**
     * 包配置
     */
    private PackageConfig getPackageConfig(CoffeeCodeGeneratorConfig coffeeConfig) {
        PackageConfig pc = new PackageConfig();
        pc.setParent(coffeeConfig.getPackageParentPath());  // 包路径 eg.  com.coffee
        pc.setModuleName(coffeeConfig.getPackageModuleName());  // eg. user;   生成的包路径： com.coffee.user
        pc.setEntity("entity");
        pc.setController("controller");
        pc.setMapper("mapper");
        return pc;
    }

    public static void main(String[] args) {
        CoffeeCodeGenerator cg = new CoffeeCodeGenerator();
        CoffeeCodeGeneratorConfig config = new CoffeeCodeGeneratorConfig();
        config.setDsDriver("org.postgresql.Driver");
        config.setDsUrl("jdbc:mysql://47.109.94.197:3306/pinghua_bss?useUnicode=true&characterEncoding=UTF-8&useSSL=false&allowMultiQueries=true");
        config.setDsUserName("postgres");
        config.setDsPassword("HYzh248713");

        config.setIncludeTableNames(new String[]{ "zhj_sys_code", "zhj_command"});
        config.setTablePrefixes(new String[]{"zhj_"});
        config.setPackageParentPath("com.hyzh.hj212");

        cg.doGenerator(config);
    }
}